<template>
  <div class="edit-account">
    <el-dialog
      title="修改收款账户"
      center
      :visible.sync="editCollection"
      :before-close="handleClose"
      width="40%"
    >
      <!-- <p class="tip" v-if="$store.state.user.vip == 0">
        您不是VIP账户
        收款账户只能填写自己收款账户。开通VIP后可添加其他人收款账户！赶快去开通吧！<router-link
          to="/agent/vip/newVIP"
          >开通VIP</router-link
        >
      </p> -->
      <el-form :model="form" :rules="ruleForm" ref="ruleForm" label-width="120px">
        <el-form-item>
          <template slot="label">
            <div class="editAccount">收款账户</div>
          </template>
          <el-select
            v-model="or_number"
            @change="drawaChanged"
            placeholder="请选择需要修改的收款账户"
          >
            <el-option
              filterable
              v-for="(item, index) in drawalList"
              :key="index"
              :label="item.num"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提现渠道" prop="type">
          <el-radio-group v-model="form.type" @change="toTypeChange">
            <el-radio :label="1" v-if="form.type == 1">支付宝</el-radio>
            <el-radio :label="2" v-if="form.type == 2">银行卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账户名" prop="payee">
          <el-input
            @change="nameChange"
            v-model="form.payee"
            :placeholder="
              form.type == 1
                ? '输入您支付宝账号绑定的身份证姓名'
                : '输入您银行卡开户身份证的姓名'
            "
          ></el-input>
        </el-form-item>
        <el-form-item :label="form.type == 1 ? '支付宝账号' : '银行卡账号'" prop="num">
          <el-input
            v-model="form.num"
            :placeholder="form.type == 1 ? '请输入支付宝账号' : '请输入银行卡账号'"
          ></el-input>
        </el-form-item>

        <template v-if="form.type == 2">
          <el-form-item label="收款银行" prop="sub_branch">
            <el-input
              v-model="form.sub_branch"
              placeholder="请输入您的开户支行"
            ></el-input>
          </el-form-item>
        </template>
        <el-form-item label="身份证号" prop="id_card_number">
          <el-input
            v-model="form.id_card_number"
            placeholder="请输入您的身份证号"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证(正面)" prop="frontUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :show-file-list="false"
            :on-success="handleSuccess1"
            :auto-upload="true"
            :before-upload="beforeUpload1"
          >
            <img v-if="frontUrl" :src="frontUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证(反面)" prop="frontUrl2">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :show-file-list="false"
            :on-success="handleSuccess2"
            :auto-upload="true"
            :before-upload="beforeUpload2"
          >
            <img v-if="frontUrl2" :src="frontUrl2" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="默认收款人">
          <el-radio-group v-model="form.default_payee" @change="toPayeeChange">
            <el-radio :label="1">默认</el-radio>
            <el-radio
              :label="2"
              :disabled="
                $store.state.user.vip == 0 && $store.state.user.name == form.payee
              "
              >不默认</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="劳务合同" v-if="$store.state.user.role_id == 2">
          <el-checkbox class="ml10" v-model="isRead"></el-checkbox>我已阅读并同意
          <span style="cursor: pointer" @click="provision">
            <font class="font_success">劳务合同协议书</font>
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="deleteZ">删 除</el-button>
        <el-button type="primary" @click="submit('ruleForm')">修 改</el-button>
      </div>
    </el-dialog>
    <agreement ref="agreement"></agreement>
  </div>
</template>

<script>
import axios from "axios";
import agreement from "~/components/agreement";
export default {
  data() {
    return {
      cardf_img: false,
      cardb_img: false,
      isRead: true,
      // drawalList: [],
      isRead: true,
      frontUrl: "",
      frontUrl2: "",
      editCollection: false,
      baseUrl: global.baseurl,
      uploadImgUrl: global.baseurl + "/api/upload/img",
      form: {
        id: "",
        type: "",
        num: "",
        bankNum: "",
        payee: "",
        sub_branch: "",
        frontUrl: "",
        frontUrl2: "",
        id_card_back: "",
        default_payee: "",
        id_card_number: "",
        id_card_front: "",
      },
      or_number: "",
    };
  },
  computed: {
    ruleForm() {
      var Validateid_card = function (rule, value, callback) {
        if (value === "" || value == undefined || value == null) {
          callback(new Error("请输入身份证号"));
        } else {
          if (
            !/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(
              value
            )
          ) {
            callback(new Error("请输入正确的身份证号"));
          } else {
            callback();
          }
        }
      };
      var validatorName = function (rule, value, callback) {
        if (value === "" || value == undefined || value == null) {
          callback(new Error("请输入账号姓名"));
        } else {
          if (!/^[\u2E80-\u9FFF]+$/.test(value)) {
            callback(new Error("请输入正确的账号姓名"));
          } else {
            callback();
          }
        }
      };
      var validatorBank = function (rule, value, callback) {
        if (value === "" || value == undefined || value == null) {
          callback(new Error("请输入银行卡号"));
        } else {
          if (!/^(?:[1-9]{1})(?:\d{15}|\d{18})$/.test(value)) {
            callback(new Error("请输入正确的银行卡号"));
          } else {
            callback();
          }
        }
      };
      var validatorNumber = function (rule, value, callback) {
        if (value === "" || value == undefined || value == null) {
          callback(new Error("请输入支付宝账号"));
        } else {
          if (
            !/^(?:1[3-9]\d{9}|[a-zA-Z\d._-]*\@[a-zA-Z\d.-]{1,10}\.[a-zA-Z\d]{1,20})$/.test(
              value
            )
          ) {
            callback(new Error("请输入正确的支付宝账号"));
          } else {
            callback();
          }
        }
      };
      return {
        type: [{ required: true, message: "请选择提现渠道", trigger: "blur" }],
        num: [
          {
            required: true,
            validator: this.form.type == 1 ? validatorNumber : validatorBank,
          },
        ],
        bankNum: [{ required: true, validator: validatorBank }],
        payee: [{ required: true, validator: validatorName }],
        sub_branch: [{ required: true, message: "请输入支行名称", trigger: "blur" }],
        frontUrl: [{ required: true, message: "请上传身份证正面照片", trigger: "blur" }],
        frontUrl2: [{ required: true, message: "请上传身份证反面照片", trigger: "blur" }],
        default_payee: [
          { required: true, message: "请选择是否默认收款人", trigger: "blur" },
        ],
        id_card_number: [{ required: true, validator: Validateid_card }],
      };
    },
  },
  components: {
    agreement,
  },
  created() {
    // this.getDrawal();
  },
  props: ["drawalList"],
  methods: {
    drawaChanged(val) {},
    nameChange() {
      // if (
      //   this.form.payee == this.$store.state.user.name &&
      //   this.$store.state.user.vip == 0
      // ) {
      //   this.form.default_payee = 1;
      // }
    },
    change(e) {
      this.$forceUpdate();
    },
    handleClose() {
      // this.$emit('refresh')
      this.editCollection = false;
    },
    //   删除收款账户
    deleteZ() {
      this.$axios.delete(`api/withdrawal/${this.form.id}`).then((res) => {
        if (res.data.code == 200) {
          this.editCollection = false;
          this.$emit("refresh");
          this.$alert("收款账户删除成功！", "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "warning",
            callback: (action) => {},
          });
        } else {
          this.$alert(res.data.message, "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "warning",
            callback: (action) => {},
          });
        }
      });
    },
    // getDrawal() {
    //   this.$axios.get("api/withdrawal").then((res) => {
    //     if (res.data.code == 200) {
    //       this.drawalList = res.data.data;
    //       for (let i = 0; i < this.drawalList.length; i++) {
    //         if (this.drawalList[i].id_card_im) {
    //           this.drawalList[i].id_card_img = JSON.parse(this.drawalList[i].id_card_img);
    //         }
    //       }
    //     } else {
    //       this.$alert(res.data.message, "提示", {
    //         confirmButtonText: "确定",
    //         center: true,
    //         type: "warning",
    //         callback: (action) => {},
    //       });
    //     }
    //   });
    // },
    // 打开协议
    provision() {
      let roleForm = {
        id_card_number: this.form.id_card_number,
        bank_card: this.form.num,
        register_bank: this.form.sub_branch,
      };
      this.$refs["agreement"].show(roleForm);
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isRead) {
            var formData = new FormData();
            formData.append("id", this.form.id);
            formData.append("payee", this.form.payee);
            formData.append("type", this.form.type);
            formData.append("default_payee", this.form.default_payee);
            // if(this.form.type == 1){
            //   formData.append("num", this.form.num);
            // }
            if (this.cardf_img) {
              formData.append("id_card_front", this.form.id_card_front);
            }
            if (this.cardb_img) {
              formData.append("id_card_back", this.form.id_card_back);
            }
            formData.append("id_card_number", this.form.id_card_number);
            if (this.form.type == 2) {
              formData.append("num", this.form.bankNum);
              formData.append("sub_branch", this.form.sub_branch);
            } else {
              formData.append("num", this.form.num);
            }
            axios({
              method: "post",
              url: this.baseUrl + "/api/withdrawal/update_withdrawal",
              data: formData,
              headers: {
                "Content-Type": "multipart/form-data",
                Authorization: "Bearer " + this.$store.state.token,
              },
            }).then((res) => {
              if (res.data.code == 200) {
                if (this.form.default_payee == 1) {
                  let id = res.data.data.id;
                  this.$axios.put(`api/withdrawal/${id}/set_default`).then((res) => {
                    if (res.data.code == 200) {
                      this.editCollection = false;
                      this.$emit("refresh");
                      this.$alert("收款账户修改成功！", "提示", {
                        confirmButtonText: "确定",
                        callback: (action) => {},
                      });
                    } else {
                      this.$alert(res.data.message, "提示", {
                        confirmButtonText: "确定",
                        center: true,
                        type: "warning",
                        callback: (action) => {},
                      });
                    }
                  });
                } else {
                  this.editCollection = false;
                  this.$emit("refresh");
                  this.$alert("收款账户修改成功！", "提示", {
                    confirmButtonText: "确定",
                    callback: (action) => {},
                  });
                }
              } else {
                this.$alert(res.data.message, "提示", {
                  confirmButtonText: "确定",
                  center: true,
                  type: "warning",
                  callback: (action) => {},
                });
              }
            });
          } else {
            this.$alert("请阅读并同意劳务合同", "提示", {
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }
        }
      });
    },
    show(data) {
      // this.form = data;
      this.form.id = data.id;
      this.form.type = data.type;
      this.form.default_payee = data.default_payee;
      this.form.id_card_number = data.id_card_number;
      this.form.payee = data.payee;
      if (data.type == 1) {
        this.form.num = data.num;
      } else {
        this.form.bankNum = data.num;
        this.form.sub_branch = data.sub_branch;
      }
      if (data.id_card_img) {
        let id_card = JSON.parse(data.id_card_img);
        this.form.id_card_back = id_card.id_card_back_thumb;
        this.form.id_card_front = id_card.id_card_front_thumb;
      }

      this.frontUrl2 = `${this.baseUrl}/storage/upload/${this.form.id_card_back}`;
      this.frontUrl = `${this.baseUrl}/storage/upload/${this.form.id_card_front}`;
      this.form.frontUrl = this.frontUrl;
      this.form.frontUrl2 = this.frontUrl2;
      this.editCollection = true;
    },
    toTypeChange(val) {
      this.form.num = "";
      this.form.bankNum = "";
    },
    toPayeeChange(val) {},
    handleSuccess1(res, file, fileList) {
      this.cardf_img = true;
      if (res.code == 200) {
        this.frontUrl = `${this.baseUrl}/storage/upload/${res.data}`;
        this.form.id_card_front = file.raw;
      } else {
        this.$alert(res.message, "提示", {
          confirmButtonText: "确定",
          callback: (action) => {},
        });
      }
    },
    beforeUpload1(file) {
      let that = this;
      let canUpload = true; //是否能够上传（布尔值）
      let type = file.name.substring(file.name.lastIndexOf(".") + 1);
      //不区分大小写
      if (!/jpg|jpeg|png|gif/i.test(type)) {
        that.$message({
          message: "文件格式只能是jpg/jpeg/png/gif",
          type: "warning",
        });
        canUpload = false;
      }
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        that.$message({
          message: "文件大小不能超过10M",
          type: "warning",
        });
        canUpload = false;
      }
      return canUpload;
    },
    handleSuccess2(res, file, fileList) {
      this.cardb_img = true;
      if (res.code == 200) {
        this.frontUrl2 = `${this.baseUrl}/storage/upload/${res.data}`;
        this.form.id_card_back = file.raw;
      } else {
        this.$alert(res.message, "提示", {
          confirmButtonText: "确定",
          callback: (action) => {},
        });
      }
    },
    beforeUpload2(file) {
      let that = this;
      let canUpload = true; //是否能够上传（布尔值）
      let type = file.name.substring(file.name.lastIndexOf(".") + 1);
      //不区分大小写
      if (!/jpg|jpeg|png|gif/i.test(type)) {
        that.$message({
          message: "文件格式只能是jpg/jpeg/png/gif",
          type: "warning",
        });
        canUpload = false;
      }
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        that.$message({
          message: "文件大小不能超过10M",
          type: "warning",
        });
        canUpload = false;
      }
      return canUpload;
    },
  },
};
</script>

<style lang="less" type="text/css">
.edit-account {
  .el-select {
    width: 100%;
  }
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 200px;
    height: 100px;

    .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .avatar {
      width: 200px;
      height: 100px;
      display: block;
    }
  }
  .editAccount {
    font-size: 17px;
    color: #008b45;
  }
  .tip {
    padding-left: 20px;
  }
}
</style>
